<template>
  <div class="matching-rule-view">
    <div class="matching-rule-view__top flex items-center text-[#83858A]">
      <div class="w-[168px]">标头类型</div>
      <div class="w-[150px]">标头名称</div>
      <div class="flex-1">值</div>
      <div class="w-[64px] text-center">操作</div>
    </div>
    <div class="matching-rule-view__body">
      <div class="matching-group">
        <div class="container">
          <http-header
            v-for="(item, index) in list"
            :key="item.uuid"
            ref="httpHeaderRefs"
            :disable-delete="headers.length === 1"
            :header="item"
            @add="addHeaderRule"
            @delete="handleDelete(index)"></http-header>
        </div>
      </div>
    </div>
    <div class="matching-rule-view__footer">
      <a-button type="text" @click="addHeaderRule">
        <i-icons-table-add />
        设置新标头
      </a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { omit } from 'lodash-es'
import { v4 as uuidV4 } from 'uuid'

import HttpHeader from './HttpHeader.vue'
import type { HeaderRule } from './types'

interface IEmit {
  (event: 'update:headers', value: HeaderRule[]): void
}

interface IProps {
  headers: HeaderRule[]
}

const emit = defineEmits<IEmit>()
const props = defineProps<IProps>()

const httpHeaderRefs = ref()

const list = useVModel(props, 'headers', emit)

// 添加新增规则
function addHeaderRule() {
  list.value.push({ uuid: uuidV4(), action: undefined, key: '', value: '' })
}

// 处理删除
function handleDelete(index: number) {
  list.value.splice(index, 1)
}

// 生成规则
function generate() {
  return list.value.map((item) => {
    return omit(item, ['uuid', 'action'])
  })
}

// 重置
function reset() {
  list.value = [{ uuid: uuidV4(), action: undefined, key: '', value: '' }]
}

async function validate() {
  return await Promise.all(
    httpHeaderRefs.value.map((item: any) => item?.validate())
  )
}

defineExpose({ generate, reset, validate })
</script>

<style scoped lang="less"></style>
